package com.ruikc.study.demo.util;

import io.github.resilience4j.common.ratelimiter.configuration.RateLimiterConfigCustomizer;
import io.github.resilience4j.ratelimiter.RateLimiterRegistry;
import io.github.resilience4j.ratelimiter.RequestNotPermitted;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;


@Aspect
@Component
public class RateLimitAspect {
    
    @Autowired
    @Lazy
    private RateLimiterRegistry rateLimiterRegistry;

    @Around("@annotation(rateLimit)")
    public Object around(ProceedingJoinPoint joinPoint, RateLimit rateLimit) throws Throwable {
        // 使用 rateLimit.value() 获取配置名称
        var rateLimiter = rateLimiterRegistry.rateLimiter(rateLimit.value());
        
         // 尝试获取令牌
         if (!rateLimiter.acquirePermission()) {
            // 通过静态工厂方法创建异常
            throw RequestNotPermitted.createRequestNotPermitted(rateLimiter);
        }
        return joinPoint.proceed();
    }

    @Bean
    public RateLimiterConfigCustomizer rateLimiterConfigCustomizer() {
        return RateLimiterConfigCustomizer.of("releaseLimiter", consumer -> {
            consumer.writableStackTraceEnabled(false); // 仅限旧版本
        });
    }
}